#endcoding:utf-8
class AnswersController < ApplicationController
  before_action :logged_in?
  layout 'user'
  def new
    @question = Question.find(params[:question_id])
    if Answer.where('question_id='+params[:question_id].to_s+' AND user_id='+uid).any?
      flash[:danger] = '您已经回答过这问题，不能重复作答'
      redirect_to question_path(@question)
    else
      @answer = Answer.new
      if @question.user_id==session[:user_id]
        flash[:danger] = '不能回答自己的问题'
        redirect_to question_path(@question)
      end
    end
  end
  def create
      @answer = Answer.new(answer_params)
      @question = Question.find(params[:answer][:question_id])
      if @answer.save
        @link = question_url(@question)
        UserMailer.account_activation(User.find(@question.user_id),"answer",@link).deliver
        redirect_to @question
      else
        flash[:danger] = @answer.errors.full_messages[0]
        render 'new'
      end
  end
  private
  def answer_params
    params.require(:answer).permit(:content,:user_id,:question_id)
  end
end
